#include "TextureDictionary.hpp"
#include "tinyxml/tinyxml.h"
#include "XmlUtil.hpp"

namespace fge
{

TextureDictionary::TextureDictionary()
{
}

TextureDictionary* TextureDictionary::FromFile(const std::string &filename)
{
	TextureDictionary *textureDictionary = new TextureDictionary();

	TiXmlDocument xmlDocument;
	bool isLoaded = xmlDocument.LoadFile(filename);

	if(isLoaded)
	{
		// todo: need sensible error handling here.
		// Bad things will happen if malformed xml is received here.
		TiXmlElement *imageElement = xmlDocument.FirstChildElement()->FirstChildElement("Image");

		while(imageElement != NULL)
		{
			std::string name = imageElement->Attribute("name");

			TextureRegion textureRegion;
			textureRegion.rect.x = StringToNumber<int>(imageElement->FirstChildElement("x")->FirstChild()->Value());
			textureRegion.rect.y = StringToNumber<int>(imageElement->FirstChildElement("y")->FirstChild()->Value());
			textureRegion.rect.w = StringToNumber<int>(imageElement->FirstChildElement("width")->FirstChild()->Value());
			textureRegion.rect.h = StringToNumber<int>(imageElement->FirstChildElement("height")->FirstChild()->Value());
			textureRegion.origin.X() = StringToNumber<float>(imageElement->FirstChildElement("xorigin")->FirstChild()->Value());
			textureRegion.origin.Y() = StringToNumber<float>(imageElement->FirstChildElement("yorigin")->FirstChild()->Value());

			textureDictionary->dictionary[name] = textureRegion;

			imageElement = imageElement->NextSiblingElement("Image");
		}

		return textureDictionary;
	}
	else
	{
		delete textureDictionary;
		return NULL;
	}
}

bool TextureDictionary::ContainsTexture(const std::string &textureName)
{
	return dictionary.count(textureName) == 1;
}

TextureRegion& TextureDictionary::GetRegion(const std::string &file)
{
	return dictionary[file];
}

}
